package org.example.game;

import org.example.game.entity.Tank;
import org.example.game.entity.Bullet;
import org.example.game.entity.Wall;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;

public class GamePanel extends JPanel implements ActionListener, KeyListener {
    private static List<Wall> walls = new ArrayList<>();
    private static List<Tank> tanks = new ArrayList<>();
    private List<Bullet> bullets;
    private Timer timer;
    private TankGame tankGame;
    private boolean isPaused = false;
    private TankGame.GameMode gameMode;

    public GamePanel(TankGame tankGame) {
        this.tankGame = tankGame;
        setBackground(Color.BLACK);
        setFocusable(true);
        addKeyListener(this);
        
        bullets = new ArrayList<>();
        timer = new Timer(16, this); // 约60FPS
    }

    public void startGame(TankGame.GameMode mode) {
        this.gameMode = mode;
        tanks.clear();
        bullets.clear();
        walls.clear();
        isPaused = false;
        
        initializeGame(mode);
        timer.start();
        requestFocus();
    }

    private void initializeGame(TankGame.GameMode mode) {
        // 初始化墙壁
        createWalls();
        
        // 根据游戏模式初始化坦克
        switch (mode) {
            case SINGLE_PLAYER:
                tanks.add(new Tank(100, 100, Tank.TankType.PLAYER));
                break;
            case TWO_PLAYERS:
                tanks.add(new Tank(100, 100, Tank.TankType.PLAYER));
                tanks.add(new Tank(700, 500, Tank.TankType.PLAYER2));
                break;
            case AI_MODE:
                tanks.add(new Tank(100, 100, Tank.TankType.PLAYER));
                tanks.add(new Tank(700, 500, Tank.TankType.AI));
                break;
            case NETWORK_MODE:
                tanks.add(new Tank(100, 100, Tank.TankType.PLAYER));
                // 网络模式的具体实现将在后续添加
                break;
        }
    }

    private void createWalls() {
        // 创建基本的墙壁布局
        for (int i = 0; i < 5; i++) {
            walls.add(new Wall(200 + i * 100, 200));
            walls.add(new Wall(200 + i * 100, 400));
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (!isPaused) {
            updateGame();
            repaint();
        }
    }

    private void updateGame() {
        // 更新坦克位置和状态
        for (Tank tank : tanks) {
            if (tank.isDestroyed()) {
                if (System.currentTimeMillis() - tank.getDestroyedTime() > Tank.getRespawnTime()) {
                    tank.respawn();
                }
            } else {
                tank.update();
                if (tank.getTankType() == Tank.TankType.AI) {
                    updateAI(tank);
                }
            }
        }
        
        // 更新子弹位置并检查碰撞
        for (int i = bullets.size() - 1; i >= 0; i--) {
            Bullet bullet = bullets.get(i);
            bullet.update();
            
            // 检查子弹是否超出边界
            if (bullet.getX() < 0 || bullet.getX() > getWidth() || 
                bullet.getY() < 0 || bullet.getY() > getHeight()) {
                bullets.remove(i);
                continue;
            }
            
            // 检查子弹碰撞
            checkBulletCollisions(bullet, i);
        }
    }

    private void updateAI(Tank aiTank) {
        // 移除AI移动逻辑，只保留射击
        if (Math.random() < 0.05) { // 5%的概率发射子弹
            Bullet bullet = aiTank.fire();
            if (bullet != null) {
                bullets.add(bullet);
            }
        }
    }

    private void checkBulletCollisions(Bullet bullet, int bulletIndex) {
        // 检查子弹与墙壁碰撞
        for (Wall wall : walls) {
            if (bullet.intersects(wall)) {
                bullets.remove(bulletIndex);
                return;
            }
        }
        
        // 检查子弹与坦克碰撞
        for (Tank tank : tanks) {
            if (bullet.getOwner() != tank && bullet.intersects(tank) && !tank.isDestroyed()) {
                bullets.remove(bulletIndex);
                tank.damage(25);  // 每颗子弹造成25点伤害
                return;
            }
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (!isPaused) {
            for (Tank tank : tanks) {
                tank.handleKeyRelease(e.getKeyCode());
            }
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
        // 不需要实现
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
            if (!isPaused) {
                showPauseMenu();
            } else {
                resumeGame();
            }
            return;
        }
        
        if (!isPaused) {
            for (Tank tank : tanks) {
                tank.handleKeyPress(e.getKeyCode());
                Bullet bullet = tank.fire();
                if (bullet != null) {
                    bullets.add(bullet);
                }
            }
        }
    }

    // 添加静态访问方法
    public static List<Wall> getWalls() {
        return walls;
    }

    public static List<Tank> getTanks() {
        return tanks;
    }

    // 添加暂停菜单
    private void showPauseMenu() {
        isPaused = true;
        timer.stop();
        
        JPanel pausePanel = new JPanel();
        pausePanel.setLayout(new BoxLayout(pausePanel, BoxLayout.Y_AXIS));
        
        JButton resumeButton = new JButton("继续游戏");
        JButton restartButton = new JButton("重新开始");
        JButton exitButton = new JButton("退出到主菜单");
        
        resumeButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        restartButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        exitButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        
        pausePanel.add(Box.createVerticalGlue());
        pausePanel.add(resumeButton);
        pausePanel.add(Box.createVerticalStrut(10));
        pausePanel.add(restartButton);
        pausePanel.add(Box.createVerticalStrut(10));
        pausePanel.add(exitButton);
        pausePanel.add(Box.createVerticalGlue());
        
        // 设置半透明背景
        pausePanel.setBackground(new Color(0, 0, 0, 128));
        pausePanel.setOpaque(true);
        
        // 添加按钮事件
        resumeButton.addActionListener(e -> resumeGame());
        restartButton.addActionListener(e -> restartGame());
        exitButton.addActionListener(e -> tankGame.returnToStart());
        
        // 将暂停菜单添加到游戏面板上
        setLayout(new BorderLayout());
        add(pausePanel, BorderLayout.CENTER);
        revalidate();
        repaint();
    }

    private void resumeGame() {
        isPaused = false;
        timer.start();
        setLayout(null); // 移除暂停菜单
        removeAll();
        revalidate();
        repaint();
    }

    private void restartGame() {
        isPaused = false;
        startGame(gameMode);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        
        // 绘制游戏元素
        for (Wall wall : walls) {
            wall.draw(g);
        }
        
        for (Tank tank : tanks) {
            tank.draw(g);
        }
        
        for (Bullet bullet : bullets) {
            bullet.draw(g);
        }
        
        // 如果游戏暂停，添加半透明遮罩
        if (isPaused) {
            g.setColor(new Color(0, 0, 0, 128));
            g.fillRect(0, 0, getWidth(), getHeight());
        }
    }
} 